package io.chenglicun.modules.evaluation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.chenglicun.common.entity.BaseEntity;
import io.chenglicun.common.page.PageData;
import io.chenglicun.common.service.impl.CrudServiceImpl;
import io.chenglicun.modules.evaluation.dao.ClcEvaluationDao;
import io.chenglicun.modules.evaluation.dao.ClcEvaluationTemplateDao;
import io.chenglicun.modules.evaluation.dto.ClcEvaluationDTO;
import io.chenglicun.modules.evaluation.entity.ClcEvaluationEntity;
import io.chenglicun.modules.evaluation.entity.ClcEvaluationTemplateEntity;
import io.chenglicun.modules.evaluation.service.ClcEvaluationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 测评管理
 *
 * @author HB 137664951@qq.com
 * @since 1.0 2023-11-28
 */
@Service
public class ClcEvaluationServiceImpl extends CrudServiceImpl<ClcEvaluationDao, ClcEvaluationEntity, ClcEvaluationDTO> implements ClcEvaluationService {

    @Autowired
    private ClcEvaluationTemplateDao templateDao;

    @Override
    public QueryWrapper<ClcEvaluationEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<ClcEvaluationEntity> wrapper = new QueryWrapper<>();


        return wrapper;
    }

    @Override
    public PageData<ClcEvaluationDTO> page(Map<String, Object> params) {
        PageData<ClcEvaluationDTO> page = super.page(params);
        List<ClcEvaluationDTO> list = page.getList();
        this.setData(list.toArray(new ClcEvaluationDTO[0]));
        return page;
    }

    @Override
    public List<ClcEvaluationDTO> list(Map<String, Object> params) {
        List<ClcEvaluationDTO> list = super.list(params);
        this.setData(list.toArray(new ClcEvaluationDTO[0]));
        return list;
    }

    @Override
    public ClcEvaluationDTO get(Long id) {
        ClcEvaluationDTO dto = super.get(id);
        this.setData(dto);
        return dto;
    }

    private void setData(ClcEvaluationDTO... dtos) {
        if (dtos == null || dtos.length == 0) return;
        List<Long> templateIds = Arrays.stream(dtos).filter(Objects::nonNull)
                .map(ClcEvaluationDTO::getTemplateId).collect(Collectors.toList());

        List<ClcEvaluationTemplateEntity> templateEntities = templateDao.selectList(
                new QueryWrapper<ClcEvaluationTemplateEntity>().lambda().in(BaseEntity::getId, templateIds));

        for (ClcEvaluationDTO dto : dtos) {
            if (dto != null) {
                ClcEvaluationTemplateEntity templateEntity = templateEntities.stream()
                        .filter(t -> t.getId().equals(dto.getTemplateId())).findFirst().orElse(null);
                dto.setTemplateName(templateEntity == null ? null : templateEntity.getName());
            }
        }
    }
}